import { defineStore } from 'pinia'
import axios from 'axios'

export const useUserStore = defineStore('user', {
  state: () => ({
    userId: null,
    username: '',
    token: '',
    isAdmin: false
  }),

  getters: {
    isAuthenticated: (state) => !!state.token
  },

  actions: {
    async login(credentials) {
      try {
        const response = await axios.post('/api/auth/login', {
          username: credentials.username,
          password: credentials.password
        }, {
          headers: { 'Content-Type': 'application/json' }
        })
        this.setUser(response.data.data)
        console.log(response.data.data)
        
        const userId = response.data.data.user.id
        localStorage.setItem('userId', userId)
        const token = response.data.data.token
        localStorage.setItem('token', token)
        return true
      } catch (error) {
        console.error('Login error:', error)
        return false
      }
    },

    async register(userData) {
      try {
        // 这里替换为实际的API调用
        // const response = await axios.post('/api/auth/register', userData)
        
        // 模拟注册成功
        return true
      } catch (error) {
        console.error('Register error:', error)
        return false
      }
    },

    logout() {
      this.userId = null
      this.username = ''
      this.token = ''
      this.isAdmin = false
      localStorage.removeItem('token')
    },
    
    setUser(userData) {
      this.userId = userData.user.userId
      this.username = userData.user.username
      this.token = userData.token
      this.isAdmin = userData.user.isAdmin
    },

    async checkAuth() {
      // 如果有token，检查token有效性
      if (this.token) {
        try {
          // 这里替换为实际的API调用来验证token
          // const response = await axios.get('/api/auth/me', {
          //   headers: { Authorization: `Bearer ${this.token}` }
          // })
          
          // 模拟验证成功
          return true
        } catch (error) {
          // Token无效，清除用户状态
          this.logout()
          return false
        }
      }
      return false
    }
  }
})